package org.jeecg.modules.putstorage.controller;

import java.io.UnsupportedEncodingException;
import java.io.IOException;
import java.math.BigDecimal;
import java.net.URLDecoder;
import java.util.*;
import java.util.stream.Collectors;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import lombok.var;
import org.jeecg.modules.ZcglTypeSettings.entity.ZcglTypeSettings;
import org.jeecg.modules.ZcglTypeSettings.service.IZcglTypeSettingsService;
import org.jeecg.modules.putstorage.util.Serialnumber;
import org.jeecg.modules.zcgl.entity.AssetFixed;
import org.jeecg.modules.zcgl.service.IAssetFixedCategoryService;
import org.jeecg.modules.zcgl.service.IAssetFixedService;
import org.jeecg.modules.zcglRecipients.entity.ZcglRecipients;
import org.jeecg.modules.zcglRecipients.entity.ZcglRecipientsAssets;
import org.jeecg.modules.zcglRecipients.service.IZcglRecipientsService;
import org.jeecg.modules.zcglsupplies.entity.ZcglSupplies;
import org.jeecg.modules.zcglsupplies.service.IZcglSuppliesService;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.jeecg.common.system.vo.LoginUser;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.putstorage.entity.ZcglPutStorageAssets;
import org.jeecg.modules.putstorage.entity.ZcglPutStorage;
import org.jeecg.modules.putstorage.vo.ZcglPutStoragePage;
import org.jeecg.modules.putstorage.service.IZcglPutStorageService;
import org.jeecg.modules.putstorage.service.IZcglPutStorageAssetsService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import com.alibaba.fastjson.JSON;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jeecg.common.aspect.annotation.AutoLog;

/**
 * @Description: 物资入库表
 * @Author: jeecg-boot
 * @Date: 2022-10-17
 * @Version: V1.0
 */
@Api(tags = "物资入库表")
@RestController
@RequestMapping("/putstorage/zcglPutStorage")
@Slf4j
public class ZcglPutStorageController {
    @Autowired
    private IZcglPutStorageService zcglPutStorageService;
    @Autowired
    private IZcglPutStorageAssetsService zcglPutStorageAssetsService;


    @Autowired
    private IAssetFixedCategoryService assetFixedCategoryService;
    @Autowired
    private IAssetFixedService assetFixedService;

    @Autowired
    private IZcglSuppliesService iZcglSuppliesService;
    @Autowired
    private IZcglRecipientsService iZcglRecipientsService;

    @Autowired
    private IZcglTypeSettingsService iZcglTypeSettingsService;
    /**
     * 分页列表查询
     *
     * @param zcglPutStorage
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @AutoLog(value = "物资入库表-分页列表查询")
    @ApiOperation(value = "物资入库表-分页列表查询", notes = "物资入库表-分页列表查询")
    @GetMapping(value = "/list")
    public Result<?> queryPageList(ZcglPutStorage zcglPutStorage,
                                   @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                   @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                   HttpServletRequest req) {

        if(zcglPutStorage.getAssetId()!=null){
            //代表有物资，走另外一条sql查询
            Page<ZcglPutStorage> page = new Page<ZcglPutStorage>(pageNo, pageSize);
            Map map = new HashMap();
            map.put("id",zcglPutStorage.getAssetId());
            map.put("storage",zcglPutStorage.getStorage());
            map.put("putDepartment",zcglPutStorage.getPutDepartment());

            map.put("curPage",(page.getCurrent() - 1) * page.getSize());
            map.put("pageSize",page.getSize());


            List<ZcglPutStorage> list = zcglPutStorageService.listByAsset(map);
            page.setRecords(list);


            return Result.ok(page);
        }

        QueryWrapper<ZcglPutStorage> queryWrapper = QueryGenerator.initQueryWrapper(zcglPutStorage, req.getParameterMap());
        queryWrapper.orderByDesc("create_time");
        Page<ZcglPutStorage> page = new Page<ZcglPutStorage>(pageNo, pageSize);
        IPage<ZcglPutStorage> pageList = zcglPutStorageService.page(page, queryWrapper);
        return Result.ok(pageList);
    }

    /**
     * 添加
     *
     * @param zcglPutStoragePage
     * @return
     */
    @AutoLog(value = "物资入库表-添加")
    @ApiOperation(value = "物资入库表-添加", notes = "物资入库表-添加")
    @PostMapping(value = "/add")
    public Result<?> add(@RequestBody ZcglPutStoragePage zcglPutStoragePage) {
        int count = zcglPutStorageService.totayCount() + 1;
        String code = "";
        String type = "";
//        if (assetFixedCategoryService.getById(zcglPutStoragePage.getStorage()).getName().contains("办公")) {
//            type = "BGYP";
//        } else if (assetFixedCategoryService.getById(zcglPutStoragePage.getStorage()).getName().contains("损耗")) {
//            type = "DZYHP";
//        } else {
//            type = "CHWZ";
//        }
        type = "WZRK";
        if (count < 10) {
            code = type + Serialnumber.getStringDate() + "00" + count;
        } else {
            code = type + Serialnumber.getStringDate() + "0" + count;
        }
        ZcglPutStorage zcglPutStorage = new ZcglPutStorage();
        BeanUtils.copyProperties(zcglPutStoragePage, zcglPutStorage);
        zcglPutStorage.setOrderCode(code);
        zcglPutStorageService.saveMain(zcglPutStorage, zcglPutStoragePage.getZcglPutStorageAssetsList());

        List list = new ArrayList();
        //去固定资产表存储 固定资产   如果走流程，下面这段代码需要放在监听结束事件里头
        for (int i = 0; i <  zcglPutStoragePage.getZcglPutStorageAssetsList().size(); i++) {
            ZcglPutStorageAssets zcglPutStorageAssets = zcglPutStoragePage.getZcglPutStorageAssetsList().get(i);
            AssetFixed assetFixed = assetFixedService.getOne(new QueryWrapper<AssetFixed>().eq("code",zcglPutStorageAssets.getAssetCode()).eq("asset_fixed_category_id",zcglPutStoragePage.getStorage()));
            if(assetFixed!=null){
                BigDecimal counts = assetFixed.getAmount().add(zcglPutStorageAssets.getAssetAmount());
                //需要更新库房里面的单价，平均价格 平均价格计算法则
                BigDecimal total = assetFixed.getPrice().multiply(assetFixed.getAmount()).add(zcglPutStorageAssets.getAssetAmount().multiply(zcglPutStorageAssets.getAssetPrice()));
                assetFixed.setAmount(assetFixed.getAmount().add(zcglPutStorageAssets.getAssetAmount()));
                BigDecimal price = new BigDecimal(0.0);
                if(counts.compareTo(BigDecimal.ZERO)!=0){

                    price = total.divide(counts, 2, BigDecimal.ROUND_HALF_UP);

                }

                assetFixed.setPrice(price);
                assetFixed.setAssetFixedCategoryId(zcglPutStorage.getStorage());
                assetFixedService.updateById(assetFixed);
            }else{

                List list1 = assetFixedService.list(new QueryWrapper<AssetFixed>().eq("code",zcglPutStorageAssets.getAssetCode()));


                AssetFixed assetFixed1 = new AssetFixed();
                //复制之前的属性
                BeanUtils.copyProperties(list1.get(0), assetFixed1);
                assetFixed1.setId(UUID.randomUUID().toString().substring(0,32));
                assetFixed1.setPrice(zcglPutStorageAssets.getAssetPrice());
                assetFixed1.setAssetFixedCategoryId(zcglPutStorage.getStorage());
                assetFixed1.setAmount(zcglPutStorageAssets.getAssetAmount());
                System.out.println("查看鑫的属性"+assetFixed1);
                assetFixedService.save(assetFixed1);
            }
            //先判断仓库有没有，有就修改数量，没有就新增一条记录

            //判断自动入库
            AssetFixed assetFixed1 = assetFixedService.getOne(new QueryWrapper<AssetFixed>().eq("code",zcglPutStorageAssets.getAssetCode()).eq("asset_fixed_category_id",zcglPutStoragePage.getStorage()));
            List<ZcglTypeSettings> types = iZcglTypeSettingsService.list(new QueryWrapper<ZcglTypeSettings>().eq("name",assetFixed1.getChwzType()));
            if(types.size()>0){
                list.add(zcglPutStorageAssets);
            }
        }

        //这是要出库的
        ZcglRecipients zcglRecipients = new ZcglRecipients();

        int count1 = iZcglRecipientsService.totayCount() + 1;
        String code1 = "";
        String type1 = "WZLY";
        if (count1 < 10) {
            code1 = type1 + Serialnumber.getStringDate() + "00" + count1;
        } else {
            code1 = type1 + Serialnumber.getStringDate() + "0" + count1;
        }
        zcglRecipients.setOrderNo(code1);

        zcglRecipients.setCreateBy(zcglPutStoragePage.getCreateBy());
        zcglRecipients.setCreateTime(zcglPutStoragePage.getCreateTime());
        zcglRecipients.setSysOrgCode(zcglPutStoragePage.getSysOrgCode());
        zcglRecipients.setNewDepartment(zcglPutStoragePage.getPutDepartment());
        zcglRecipients.setProcessStatus(2);//
        zcglRecipients.setRecipientsUser(zcglPutStoragePage.getPutUser());
        zcglRecipients.setDelFlag("0");
        zcglRecipients.setProcessStatusText("自动审批通过");
        List<ZcglRecipientsAssets> list1 = new ArrayList<>();
        String names = "";
        for (int i = 0; i < list.size(); i++) {
            var items = list.get(i);
            ZcglRecipientsAssets zcglRecipientsAssets = new ZcglRecipientsAssets();
            BeanUtils.copyProperties(items, zcglRecipientsAssets);
            list1.add(zcglRecipientsAssets);
            AssetFixed assetFixed = assetFixedService.getOne(new QueryWrapper<AssetFixed>().eq("code",zcglRecipientsAssets.getAssetCode()).eq("asset_fixed_category_id",zcglPutStoragePage.getStorage()));
            assetFixed.setAmount(assetFixed.getAmount().subtract(zcglRecipientsAssets.getAssetAmount()));
            assetFixedService.updateById(assetFixed);
            names += assetFixed.getName()+"/";
        }
        if(list.size()>0){
            iZcglRecipientsService.saveMain(zcglRecipients, list1);

        }
        if(list1.size()>0){
            return Result.ok("添加成功！并且物资（"+names+"）自动生成了领用单！");
        }else{
            return Result.ok("添加成功！");
        }

    }

    /**
     * 编辑
     *
     * @param zcglPutStoragePage
     * @return
     */
    @AutoLog(value = "物资入库表-编辑")
    @ApiOperation(value = "物资入库表-编辑", notes = "物资入库表-编辑")
    @PutMapping(value = "/edit")
    public Result<?> edit(@RequestBody ZcglPutStoragePage zcglPutStoragePage) {
        ZcglPutStorage zcglPutStorage = new ZcglPutStorage();
        BeanUtils.copyProperties(zcglPutStoragePage, zcglPutStorage);
        ZcglPutStorage zcglPutStorageEntity = zcglPutStorageService.getById(zcglPutStorage.getId());
        if (zcglPutStorageEntity == null) {
            return Result.error("未找到对应数据");
        }
        zcglPutStorageService.updateMain(zcglPutStorage, zcglPutStoragePage.getZcglPutStorageAssetsList());
        return Result.ok("编辑成功!");
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "物资入库表-通过id删除")
    @ApiOperation(value = "物资入库表-通过id删除", notes = "物资入库表-通过id删除")
    @DeleteMapping(value = "/delete")
    public Result<?> delete(@RequestParam(name = "id", required = true) String id) {



        zcglPutStorageService.delMain(id);
        return Result.ok("删除成功!");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "物资入库表-批量删除")
    @ApiOperation(value = "物资入库表-批量删除", notes = "物资入库表-批量删除")
    @DeleteMapping(value = "/deleteBatch")
    public Result<?> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        this.zcglPutStorageService.delBatchMain(Arrays.asList(ids.split(",")));
        return Result.ok("批量删除成功！");
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @AutoLog(value = "物资入库表-通过id查询")
    @ApiOperation(value = "物资入库表-通过id查询", notes = "物资入库表-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<?> queryById(@RequestParam(name = "id", required = true) String id) {
        ZcglPutStorage zcglPutStorage = zcglPutStorageService.getById(id);
        if (zcglPutStorage == null) {
            return Result.error("未找到对应数据");
        }
        return Result.ok(zcglPutStorage);

    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @AutoLog(value = "入库的物资明细表通过主表ID查询")
    @ApiOperation(value = "入库的物资明细表主表ID查询", notes = "入库的物资明细表-通主表ID查询")
    @GetMapping(value = "/queryZcglPutStorageAssetsByMainId")
    public Result<?> queryZcglPutStorageAssetsListByMainId(@RequestParam(name = "id", required = true) String id) {
        List<ZcglPutStorageAssets> zcglPutStorageAssetsList = zcglPutStorageAssetsService.selectByMainId(id);

        for (int i = 0; i < zcglPutStorageAssetsList.size(); i++) {
            var item = zcglPutStorageAssetsList.get(i);

           AssetFixed assetFixed  = assetFixedService.getById(item.getAssetId());
            item.setAssetName(assetFixed.getName());


        }




        return Result.ok(zcglPutStorageAssetsList);
    }

    /**
     * 导出excel
     *
     * @param request
     * @param zcglPutStorage
     */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, ZcglPutStorage zcglPutStorage) {
        // Step.1 组装查询条件查询数据
        QueryWrapper<ZcglPutStorage> queryWrapper = QueryGenerator.initQueryWrapper(zcglPutStorage, request.getParameterMap());
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();

        //Step.2 获取导出数据
        List<ZcglPutStorage> queryList = zcglPutStorageService.list(queryWrapper);
        // 过滤选中数据
        String selections = request.getParameter("selections");
        List<ZcglPutStorage> zcglPutStorageList = new ArrayList<ZcglPutStorage>();
        if (oConvertUtils.isEmpty(selections)) {
            zcglPutStorageList = queryList;
        } else {
            List<String> selectionList = Arrays.asList(selections.split(","));
            zcglPutStorageList = queryList.stream().filter(item -> selectionList.contains(item.getId())).collect(Collectors.toList());
        }

        // Step.3 组装pageList
        List<ZcglPutStoragePage> pageList = new ArrayList<ZcglPutStoragePage>();
        for (ZcglPutStorage main : zcglPutStorageList) {
            ZcglPutStoragePage vo = new ZcglPutStoragePage();
            BeanUtils.copyProperties(main, vo);
            List<ZcglPutStorageAssets> zcglPutStorageAssetsList = zcglPutStorageAssetsService.selectByMainId(main.getId());
            vo.setZcglPutStorageAssetsList(zcglPutStorageAssetsList);
            pageList.add(vo);
        }


        // Step.4 AutoPoi 导出Excel
        ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
        mv.addObject(NormalExcelConstants.FILE_NAME, "物资入库表列表");
        mv.addObject(NormalExcelConstants.CLASS, ZcglPutStoragePage.class);
        mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("物资入库表数据", "导出人:" + sysUser.getRealname(), "物资入库表"));
        mv.addObject(NormalExcelConstants.DATA_LIST, pageList);
        return mv;
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
        for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
            MultipartFile file = entity.getValue();// 获取上传文件对象
            ImportParams params = new ImportParams();
            params.setTitleRows(2);
            params.setHeadRows(1);
            params.setNeedSave(true);
            try {
                List<ZcglPutStoragePage> list = ExcelImportUtil.importExcel(file.getInputStream(), ZcglPutStoragePage.class, params);
                for (ZcglPutStoragePage page : list) {
                    ZcglPutStorage po = new ZcglPutStorage();
                    BeanUtils.copyProperties(page, po);
                    zcglPutStorageService.saveMain(po, page.getZcglPutStorageAssetsList());
                }
                return Result.ok("文件导入成功！数据行数:" + list.size());
            } catch (Exception e) {
                log.error(e.getMessage(), e);
                return Result.error("文件导入失败:" + e.getMessage());
            } finally {
                try {
                    file.getInputStream().close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return Result.ok("文件导入失败！");
    }


}
